import React from 'react';
import {
  View,
  Text,
  ScrollView,
  Image,
  TouchableOpacity,
  ProgressViewIOS,
  ProgressBarAndroid
} from 'react-native';

import {
  Button,
} from 'react-native-elements';
var ProgressBar = require('ProgressBarAndroid');
import Platform from 'Platform';
import Config from '../../config';
import TImage from '../../components/TImage';
import BasePage from '../common/BasePage';
import CommonAvatarView from '../common/CommonAvatarView';
import Constants from '../../common/Constants';
import ImageConstants from '../../common/ImageConstants';
import SizeUtils from '../../common/SizeUtils';
import Sound from 'react-native-sound';
import {AudioRecorder, AudioUtils} from 'react-native-audio';
import ToastUtils from '../../common/ToastUtils';
import ActivityRequestOneApplicantAction from '../../actions/activity/ActivityRequestOneApplicantAction';
import ActivityLikeSingerAction from '../../actions/activity/ActivityLikeSingerAction';

export default class ActivitySingerDataPage extends BasePage {
  constructor(props) {
    super(props);

    this.state.applicantData = {};
    this.state.is_liked = 0;
    this.state.loadDataSuccess = false;
    this.state.soundCurrentTime = 0;
    this.state.soundTotalTime = 0;
    this.state.likeStatus = 1;//请求状态  1正常  2请求中
    this.state.statusText = "";

    this._sound = null;
  }

  render() {
    return(
      <View style={{flex:1, backgroundColor:"#ffffff"}}>
        {this._renderHeader()}
        {this._renderCircle()}
        {this._renderUploadSound()}
        {this._renderText()}
        {this._renderBottomBar()}
        {this._renderShareView()}
      </View>
    )
  }

  componentDidMount() {
    this._requestData();
  }

  componentWillUMount() {
    this._stopPlay();
    this._sound = null;
  }

  componentWillUpdate(nextProps, nextState) {
    if(nextState.refresh || nextState.updateByLike) {
      nextState.refresh = false;
      nextState.updateByLike = false;
      this._requestData();
      if(nextState.statusText != "") {
        ToastUtils.show(nextState.statusText);
        nextState.statusText = "";
      }
    }
    if(nextState.loadDataSuccess) {
      nextState.loadDataSuccess = false;
      this._initSound();
    }
  }

  // 录音完成
   _initSound() {
    setTimeout(() => {
      this._sound = new Sound(this.state.applicantData.media_url, '', (error) => {
        if (error || this._sound === null) {
          console.log('failed to load the sound', error);
          return;
        }
        this.setState({
          soundTotalTime: this._sound._duration,
        })
      });
      //这里加载完才算完成
    }, 10);
  }

  _dealLeavePage() {
    this._stopPlay();
    this._sound = null;
    this.state.soundCurrentTime = 0;
    this.state.soundTotalTime = 0;
    this.state.applicantData = {};
    this.state.is_liked = 0;
  }

  _requestData() {
    new ActivityRequestOneApplicantAction().call(this, {
      activity_id:this.props.pageData.routeData.activity_id,
      applicant_id:this.props.pageData.routeData.applicant_id,
    })
  }

  _renderHeader() {
    // #565C60
    return(
      <View style={{flexDirection:"row", flexDirection:"row", justifyContent:"space-between",
        backgroundColor:"#42494F", paddingTop:Config.tabBarTop}}>
        {this._renderNavigationBarLeftButton()}
        {this._renderNavigationBarTitle()}
        {this._renderNavigationBarRightButton()}
      </View>
    )
  }

  _renderCircle() {
    return(
      <View style={{backgroundColor:"#42494F", flexDirection:"column", alignItems:"center",
          height:SizeUtils.translateDesignHeightToCode(360), paddingTop:SizeUtils.translateDesignHeightToCode(40),
        }}>
        <CommonAvatarView avatarUri={this.state.applicantData.avatar_url} size={212}/>
        <Text style={{fontSize:SizeUtils.translateFontSizeToCode(28), color:"#ffffff",
            paddingTop:SizeUtils.translateDesignHeightToCode(26)}}>
          {this.state.applicantData.by_name ? this.state.applicantData.by_name : "- - - -"}
        </Text>
      </View>
    )
  }

  //上传声音
  _renderUploadSound() {
    return(
      <View style={{flexDirection:"column", alignItems:"center", backgroundColor:"#ffffff"}}>
        <Text style={{paddingTop:SizeUtils.translateDesignHeightToCode(32),
            fontSize:SizeUtils.translateFontSizeToCode(34), color:"#222222", textAlign:"center"}}>
            他(她)的歌声</Text>
        {this._renderRecord()}
      </View>
    )
  }

  _renderRecord() {
    return(
      <View style={{flexDirection:"column", borderRadius:SizeUtils.translateDesignNumToCode(10), borderWidth:SizeUtils.translateDesignNumToCode(3),
        borderColor:"#eeeeee", alignItems:"center", height: SizeUtils.translateDesignHeightToCode(250)}}>
        <View style={{flexDirection:"row", alignItems:"center", marginTop:SizeUtils.translateDesignHeightToCode(30),
          width:SizeUtils.translateDesignWidthToCode(639), height:SizeUtils.translateDesignHeightToCode(76),
          alignItems:"center", justifyContent:"center"}}>
        <Text style={{color:"#999999", fontSize:SizeUtils.translateFontSizeToCode(24), marginLeft:SizeUtils.translateDesignWidthToCode(12)}}>
          {this._getCurrentTimeText()}
        </Text>
        <View style={{width:SizeUtils.translateDesignWidthToCode(410), marginLeft:SizeUtils.translateDesignWidthToCode(12),
          backgroundColor:"#cccccc00", height:SizeUtils.translateDesignHeightToCode(20)}}>
          {this._renderProgressBar()}
        </View>
        <Text style={{color:"#999999", fontSize:SizeUtils.translateFontSizeToCode(24), marginLeft:SizeUtils.translateDesignWidthToCode(7)}}>
          {this._getTotalTimeText()}
        </Text>
        </View>
        <TouchableOpacity onPress={this._onPressPlay.bind(this)} style={{height:SizeUtils.translateDesignHeightToCode(130)}}>
          <TImage source={require("../../../resource/images/common/bofang3.png")}
            style={{width:120, height:120, marginLeft:SizeUtils.translateDesignWidthToCode(10)}}/>
        </TouchableOpacity>
      </View>
    )
  }

  _renderProgressBar() {
    if(Platform.OS === "ios") {
      return(
        <ProgressViewIOS style={{height:SizeUtils.translateDesignHeightToCode(20)}}
          progressTintColor="#db3132" progress={this._getProgress()}/>
      )
    }else{
      return (
        <ProgressBarAndroid indeterminate={false}  styleAttr="Horizontal" color="black" style={{height:SizeUtils.translateDesignHeightToCode(20)}}
          progress={this._getProgress()}/>
      );
    }
  }

  _getProgress() {
    return this.state.soundCurrentTime / this.state.soundTotalTime;
  }

  _getCurrentTimeText() {
    //soundCurrentTime  单位秒
    return this._getTimeText(this.state.soundCurrentTime)
  }

  _getTotalTimeText() {
    //soundTotalTime  单位秒
    return this._getTimeText(this.state.soundTotalTime)
  }

  _getTimeText(time) {
    time = Math.ceil(time);
    if(time == 0) {
      return "00:00";
    }
    let minutes = Math.floor(time / 60);
    let second = time - minutes * 60;
    let minutesStr = minutes < 10 ? ("0" + minutes) : minutes;
    let secondStr = second < 10 ? ("0" + second) : second;
    return minutesStr + ":" + secondStr;
  }

  //点击播放声音
  _onPressPlay() {
    this._play();
  }

  _play(){
    if(this._sound == null){
      console.log("sound not find");
      return;
    }
    if(this._audioTick != null){
      console.log("还没播放完又开始了？");
      this._stopPlay();
      return;
    }
    this.setState({
      soundCurrentTime:0,
    })
    var self = this;

    this._sound.play((success) => {
      if (success) {
        console.log('successfully finished playing');
      } else {
        console.log('playback failed due to audio decoding errors');
      }
    });
    this._audioTick = setInterval(function(){
      self._sound.getCurrentTime(function(ctime){
        if(ctime == 0){
          // 播放完了
          self._clearTimer();
          self.setState({
            soundCurrentTime: self.state.soundTotalTime,
          })
        }
        else {
          self.setState({
            soundCurrentTime: ctime,
          })
        }
         console.log("播放进度:" + ctime+"秒，总时长：",self._sound._duration);
      });
    },1000);
  }

  _clearTimer() {
    if(this._audioTick != null){
      clearInterval(this._audioTick);
      this._audioTick = null;
    }
  }

  _stopPlay() {
    if(this._sound == null){
      console.log("sound not find by stop");
      return;
    }
    this._clearTimer();
    this._sound.stop();
  }

  _renderText() {
    return(
      <View style={{alignItems:"center"}}>
        <ScrollView style={{width:SizeUtils.translateDesignWidthToCode(670), paddingTop:SizeUtils.translateDesignHeightToCode(60)}}>
          <Text style={{fontSize:SizeUtils.translateFontSizeToCode(30),
              color:"#cacaca"}}>
            {this.state.applicantData.content}
          </Text>
        </ScrollView>
      </View>
    )
  }

  _renderBottomBar() {
    let shareDisabled = false;
    let likeDisable = this._checkLikeBtnDisable();
    return (
      <View style={{width:SizeUtils.getWindowSize().width, position:"absolute",
          flexDirection:"row",
          height:SizeUtils.translateDesignHeightToCode(90),
          bottom:0, justifyContent:"space-between",
          alignItems: "center", shadowColor:"#cccccc", shadowOpacity:0.8, shadowOffset:{height:SizeUtils.translateDesignNumToCode(-2)}, shadowRadius:1,
          backgroundColor:"#ffffff"}}>
          {this._renderButton(shareDisabled, "分享", this._onPressShareBtn.bind(this))}
          {this._renderButton(likeDisable, this._getLikeText(), this._onPressLikeBtn.bind(this))}
      </View>
    )
  }

  _onPressShareBtn() {
    if(this.state.applicantData){
        this.setState({showShare:true});
    }
  }

  _getShareData() {
    return {activity_id:this.props.pageData.routeData.activity_id,
      type:Constants.MODULE_TYPE.ACTIVITY,
      applicant_id:this.props.pageData.routeData.applicant_id,
      title:this.state.applicantData.by_name+"的报名信息"};
  }

  _renderButton(disabled, title, onPress) {
    return (
      <Button
          backgroundColor="#db3132"
          buttonStyle={{width:SizeUtils.translateDesignWidthToCode(320),
            marginTop:SizeUtils.translateDesignHeightToCode(5),
            height:SizeUtils.translateDesignWidthToCode(70),
            borderColor:disabled ? "#cccccc" : "#db3132",
            borderWidth:SizeUtils.translateDesignNumToCode(3),}}
          borderRadius={SizeUtils.translateDesignNumToCode(10)}
          onPress={onPress}
          title={title}
          textStyle={{color:disabled ? "#333333" : "#ffffff"}}
          disabled={disabled}
      />
    )
  }

  _checkLikeBtnDisable() {
    return this.state.is_liked > 0 || this.state.likeStatus === 2;
  }

  _onPressLikeBtn() {
    new ActivityLikeSingerAction().call(this, {
      activity_id:this.props.pageData.routeData.activity_id,
      applicant_id:this.props.pageData.routeData.applicant_id,
    });
  }

  _getLikeText() {
    let text = "";
    if(this.state.is_liked === 1) {
      text = "已投票";
    }
    else if(this.state.is_liked === 2) {
      text = "票数已用完";
    }
    else {
      text = "投票";
    }
    return text;
  }
}
